﻿using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Xsl;
using DevelopersToolbox;

namespace XmlTools {
    public partial class XslControl : UserControl, IExecutableTool {
        private const string BASIC_XSL = @"<?xml version=""1.0""?>
<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">
   <xsl:template match=""/"">
      Hello World!
   </xsl:template>
</xsl:stylesheet>";

        public XslControl() {
            InitializeComponent();
            _xslSourceSelect.SetText(BASIC_XSL);
        }

        private void _executeButton_Click(object sender, EventArgs e) {
            Execute();
        }

        public void Execute() {
            try {
                XmlDocument xmlDoc = _xmlSourceSelect.GetDataAsXml();
                XmlDocument xslDoc = _xslSourceSelect.GetDataAsXml();
                XslCompiledTransform xslTransform = new XslCompiledTransform();
                xslTransform.Load(xslDoc);
                StringBuilder sb = new StringBuilder();
                TextWriter textWriter = new StringWriter(sb);
                XmlWriter xmlWriter = XmlWriter.Create(textWriter, xslTransform.OutputSettings);
                xslTransform.Transform(xmlDoc, xmlWriter);
                _results.Text = sb.ToString();

                _xmlSourceSelect.AddTextToDropDown();
                _xslSourceSelect.AddTextToDropDown();
            }
            catch (Exception ex) {
                _results.Text = ex.ToString();
            }
        }
    }
}